<template>
  <van-nav-bar left-text="返回" left-arrow @click-left="$router.back()" />
  <div class="a">
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field v-model="username" name="用户名" label="用户名" placeholder="用户名"
          :rules="[{ validator, message: '请输入正确内容' }, { required: true, message: '请填写用户名' }]" />
        <van-field v-model="password" type="password" name="密码" label="密码" placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]" />
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit" class="van-button-denglu">
          登录
        </van-button>
        <van-button round block type="primary" native-type="submit" class="van-button-zhuce"
          @click="$router.push('/reg')">
          注册
        </van-button>

      </div>
    </van-form>
  </div>
</template>
<script>
import { loginRequset } from '@/api/userApi';
import { showFailToast, showSuccessToast } from 'vant';
export default {
  data() {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    onSubmit() {
      loginRequset({ loginname: this.username, password: this.password }).then((r) => {
        console.log("注册结果:", r.data);
        let { code, message } = r.data;
        if (code == "200") {
          let { token, userid } = r.data.data;
          localStorage.setItem("mallFrontToken", token)
          localStorage.setItem("mallFrontUserId", userid)
          this.$router.push({ path: '/' });
          showSuccessToast(message)
        } else {
          showFailToast(message)
        }
      }).catch((err) => {
        console.log("错误结果:", err)
        showFailToast("服务错误")
      });
    },
    validator(val) {
      return /^[a-zA-Z][a-zA-Z0-9_]{3,19}$/.test(val);
    },

  },
  mounted() { }
}
</script>
<style lang="css">
.a {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.van-button-denglu {
  width: 40%;
  float: left;
}

.van-button-zhuce {
  width: 40%;
  float: right;
}
</style>
